﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Traceable.App.Application.Command.Goods;
using Traceable.Domian;
using Traceable.ErrorCode;
using Traceable.Infastructure;

namespace Traceable.App.Application.Handler.Goods
{
    public class CreateGoodsTraceHandler : IRequestHandler<CreateGoodsTraceCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Traceable_Table> _traceableRepositry;
        private readonly IMapper _mapper;

        public CreateGoodsTraceHandler(IBaseRepository<Traceable_Table> traceableRepositry, IMapper mapper)
        {
            _traceableRepositry = traceableRepositry;
            _mapper = mapper;
        }
        /// <summary>
        /// 溯源基本信息新增
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(CreateGoodsTraceCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var model = _mapper.Map<Traceable_Table>(request);
            model.Perfect = 10;
            model.CreateTime= DateTime.Now;
            model.Creater = "张三";
            model.UpdateTime = null;

            var res = _traceableRepositry.Add(model);
            if(res>0)
            {
                result.Code = StatusEnum.OK;
                result.Data = res;
                result.Message = "添加成功";
            }
            else
            {
                result.Code = StatusEnum.Fail;
                result.Data = res;
                result.Message = "添加失败";
            }
            return Task.FromResult(result);
        }
    }
}
